<?php
namespace app\admin\controller;

use app\admin\model\Account as AccountModel;
use app\admin\model\AccountGroup as AccountGroupModel;
use app\admin\model\Agent as AgentModel;
use think\Db;
use think\Request;

class Account extends Base
{
    public function index()
    {
        $model = new AccountModel;
        $aGroupModel = new AccountGroupModel;
        $agentModel = new AgentModel;

        $phname = $this->request->param("phname");

        //渲染页面模板
        $model->field('u.id,u.username,u.nickname,g.name as groupname,f.name as agentname,
                                        u.franchiser_id,u.email,u.remark,u.gender,u.user_group_id,
                                        u.last_login_at, u.region_id,u.device_count,u.created_at,u.updated_at')
                        ->alias('u')
                        ->join('user_group g','u.user_group_id = g.id ','left')
                        ->join('franchiser f','u.franchiser_id = f.id','left')
                        ->order('u.id','desc');
                        //->select();
                       // ->paginate(5);

        if(!empty($phname)){
            $model->where('u.username','like', '%'.$phname.'%');
            //dump($m);exit;
        }
        
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        $items = $result->items();

        //循环数组
        $exArr=[];
        $REArr=[];
        foreach ($items as $k=>$v){
            $exArr=\think\Db::query('SELECT sum(reward) as sumex FROM '. $this->dbTablePrefix .'reward_log where user_id='.$v["id"]);
            $REArr=\think\Db::query('SELECT sum(reward) as sumRE FROM '. $this->dbTablePrefix .'task as t LEFT JOIN '. $this->dbTablePrefix .'task_user as m on t.id=m.task_id  where  m.user_id='.$v["id"] .' and m.status="5" and  t.deleted_at is null');
            if(empty($REArr[0]["sumRE"])){
                $REArr[0]["sumRE"]="0";
            }
            if(empty($exArr[0]["sumex"])){
                $exArr[0]["sumex"]="0";
            }

            $items[$k]["integral"] =$REArr[0]["sumRE"]-$exArr[0]["sumex"] ;
        }

        //渲染用户组
        $uGroup = $aGroupModel->field('id,name')->select();
        //渲染代理商
        $agent = $agentModel->field('id,name')->select();

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $id = $_POST["viewId"];
            $view = $model->field('u.id,u.username,u.nickname,u.franchiser_id,u.email,u.remark,u.gender,u.user_group_id,
                                        u.last_login_at, u.region_id,u.device_count,u.created_at,u.updated_at')
                ->alias('u')
                //->join('reward_log r','u.id = r.user_id ','left')
                ->where("u.id",$id)
                ->select();
            $reward_logArr=\think\Db::query('SELECT sum(reward) as sumex FROM '. $this->dbTablePrefix .'reward_log where user_id='.$id);
            $taskArr=\think\Db::query('SELECT sum(reward) as sumRE FROM '. $this->dbTablePrefix .'task as t LEFT JOIN '. $this->dbTablePrefix .'task_user as m on t.id=m.task_id  where  m.user_id='.$id .' and m.status="5" and  t.deleted_at is null');
            if(empty($taskArr[0]["sumRE"])){
                $taskArr[0]["sumRE"]="0";
            }
            if(empty($reward_logArr[0]["sumex"])){
                $reward_logArr[0]["sumex"]="0";
            }

            $view[0]["integral"] =$taskArr[0]["sumRE"]-$reward_logArr[0]["sumex"] ;

            return json([
                'code' => 200,
                'view'=>$view,
            ]);
        }

        $this->assign('currentPage',$result->currentPage());
        $this->assign('lastPage',$result->lastPage());
        $this->assign('page',$page);
        $this->assign('uGroup',$uGroup);
        $this->assign('agent',$agent);
        $this->assign('account',$result);
        $this->assign('count',$count);

        $this->assign('empty',"暂无数据");
        return $this->fetch();
    }

    //新增数据
    public function create(){
        $model = new AccountModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        if($ispost){
            $formdata = $this->request->post();
            $username = Db::query("select id,username from ". $this->dbTablePrefix ."user where `username`='".$formdata['username']."' and deleted_at is NULL ");
            
            if(!empty($username)){
                return json([
                    'code' => 4000,
                    'message'=>"用户名已存在"
                ]);
            }
            $result = $model->allowField(true)->save($formdata);
            
            if($result==1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //修改数据处理
    public function edit($id)
    {
        $model = new AccountModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        
        if($ispost){
            $formdata = $this->request->post();
            
            $result = $model->allowField(true)->save($formdata,['id'=>$id]);
            
            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //删除单条记录
    public function delete($id)
    {
        $result = AccountModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['id'=>$id]);//软删除
        //AccountModel::destroy($id,true);//真实删除
        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();
            
            $result = AccountModel::where('id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }
}
